package org.epanetgrid.otimizacao.evaluators;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;

import org.epanetgrid.otimizacao.searchspace.IndividualEvaluator;
import org.jheuristics.Individual;


/**
 * Evaluator que avalia outros indiv�duos a partir de uma lista de indiv�duos avaliados anteriormente
 *
 * @author Marcell Manfrin, marcell@ourgrid.org, Dec 12, 2005
 */
public class BackupIndividualEvaluator implements IndividualEvaluator {
	private Map<Object, Individual> map;

	/**
	 * Indiv�duos avaliados anteriormente que ser�o utilizados para avalia��o de outros indiv�duos
	 * @param individuals
	 */
	public BackupIndividualEvaluator(List individuals) {
		map = createMap(individuals);
	}

	/**
	 *
	 * @param individual Indiv�duo a ser avaliado
	 * @return indiv�duo avaliado, null caso o indiv�duo n�o tenha sido avaliado anteriormente
	 * @see org.epanetgrid.otimizacao.searchspace.IndividualEvaluator#evaluate(org.jheuristics.Individual)
	 */
	public Individual evaluate(Individual individual) {
		return (Individual) map.get(individual.getGens());
	}

	/**
	 * Cria mapa
	 * @param individuals Indiv�duos a serem inseridos no mapa
	 * @return
	 */
	private Map<Object, Individual> createMap(List individuals) {
//		Map<Object, Individual> result = new HashMap<Object, Individual>(individuals.size());
		Map<Object, Individual> result = new WeakHashMap<Object, Individual>(individuals.size());
		for (Iterator it = individuals.iterator(); it.hasNext(); ) {
			Individual individual = (Individual) it.next();
			result.put(individual.getGens(), individual);
		}
		return result;
	}

}
